package application.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.*;
import java.util.Properties;

public class UtilsRedis {
    private static Logger logger = LoggerFactory.getLogger(UtilsRedis.class);

    private static Properties properties = new Properties();
    private static JedisPool jedisPool = null;

    static{
        try {
            InputStream in = UtilsRedis.class.getClassLoader()
                    .getResourceAsStream("config.properties");
            properties.load(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    * 初始化Redispool，参数从配置文件中加载
    * */
    public static void RedisPoolInit() {
        JedisPoolConfig config = new JedisPoolConfig();
        int maxTotal = Integer.parseInt(properties.getProperty("redis.maxTotal","5"));
        int port = Integer.parseInt(properties.getProperty("redis.port","6379"));
        String ip = properties.getProperty("redis.ip","127.0.0.1");
        String password = properties.getProperty("redis.password","123456");
        config.setMaxTotal(maxTotal);
        config.setTestWhileIdle(true);
        config.setTestOnBorrow(false);
        config.setTestOnCreate(false);
        jedisPool = new JedisPool(config,ip,port,1000,password);
        logger.info("redis连接池初始化完成");
    }

    /*
    * 获取jedis
    * */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /*
    * 关闭redispool
    * */
    public static void RedisPoolClose() {
        jedisPool.close();
    }
}
